<?php
session_start();
require_once('../lib.php');
$avatar_redir = IMAGE_FOLDER.'/avatar/';
$avatar_default = './style/default/no_avatar.jpg';
$limitrecord_friend = 8;
$limitrecord_userrandom = 7;

if(verify_page()){
	if( isset($_GET['act']) && $_GET['act'] != ''){
		$act = $_GET['act'];
		switch($act){
			  case "myfriend": 	{	
					if( isset($_GET['val']) && $_GET['val'] != '' && isset($_GET['gru']) && $_GET['gru'] != ''){
						$val = $_GET['val'];
						$gru = $_GET['gru']; //print_r ($val);
						echo load_myfriend($gru,$val);
					}
					else{ echo '0'; }
					break;
				}
			  case "randomuser": 	{	
					echo load_randomuser();
					break;
				}
			  case "grouplist": 	{	
					if( isset($_GET['val']) && $_GET['val'] != ''){
						$val = $_GET['val'];
						if( isset($_GET['pos']) && $_GET['pos'] != ''){
							$pos = $_GET['pos'];
						} else {
							$pos = 'all';
						}
						echo load_grouplist($val,$pos);
					}
					else{ echo '0'; }
					break;
				}
			  case "newgroup": 	{	
					echo load_form_newgroup();
					break;
				}
			  case "editgroup": 	{	
					if( isset($_GET['val']) && $_GET['val'] != ''){
						$val = $_GET['val'];
						echo load_form_editgroup($val);
					}
					else{ echo '0'; }
					break;
				}
			  case "friendlist": 	{	
					if( isset($_GET['val']) && $_GET['val'] != ''){
						$val = $_GET['val'];
						echo load_form_friendlist($val);
					}
					else{ echo '0'; }
					break;
				}
			  default:		{
					echo 'Function false';
					break;
				}
		}
	}
}

function load_form_friendlist($val){
	global $avatar_redir, $avatar_default;
	$get_member = '';
	$array_list_friend ='';
	$i = 0;
	$selected_checkbox = '';
	$selected_li = '';			
	$get_friend = get_list('all');
	$get_list = get_list($val);

	if($get_list !=''){
		$get_member = explode(",", $get_list);
		$i = count($get_member);
	}
	
	include("../connect.php");
	if($get_friend!=''){
		$merg_sql = "SELECT a.`id`, a.`username`, b.`avatar`";
		$merg_sql .= " FROM `user_account` a,`user_info` b";
		$merg_sql .= " WHERE a.`id` = b.`id` AND a.`status` = '1' AND  a.`id` IN (".$get_friend.")";
		$merg_sql .= " ORDER BY a.`username` ASC";
		$result2 = mysql_query($merg_sql, $conn);
		if (mysql_num_rows($result2)!=0){
			while ($row2 = mysql_fetch_row($result2)){ 
				$array_list_friend[] = $row2;
			}
		}
		mysql_free_result($result2);			
	}
  mysql_close($conn);
	echo '<div class="close_listicon" onclick="closethis();"><img src="./style/default/close.png" border="0" /></div>';
	if($array_list_friend!=''){
		$i = ($i-1);
		echo '<div class="form_save_add_member uix-button" onclick="add_member(\''.$val.'\');"> &nbsp; SAVE &nbsp; </div>';
		echo '<ul class="style_user_notfriend">';
		foreach($array_list_friend as $each_friend => $vallist){
			if($get_member!=''){
				if($get_member[$i] == $vallist['0']){
					$selected_checkbox = 'checked="checked"';
					$selected_li = 'class="selected"';
					if($i != 0)	$i--;
				}
				else {
					$selected_checkbox = '';
					$selected_li = '';			
				}
			}
			echo '<li '.$selected_li.'>';
			if(!file_exists($avatar_redir.$vallist['2']) || $vallist['2'] == ''){
				$link_image = $avatar_default;
			} else {
				$link_image = $avatar_redir.$vallist['2'];
			}
			echo '<div class="checkbox_friend" id="bt_'.$vallist['0'].'" align="right"><input type="checkbox" name="select_friend" '.$selected_checkbox.' style="display:none;" value="'.$vallist['0'].'" /></div>';
			echo '<div class="avatar"><img src="'. $link_image .'"></div>';
			echo '<div align="center">'. $vallist['1'] .'</div>';
			echo '</li>';
		}
		echo '</ul>';
	}
	
	echo '<script>
	
	$("#loadlistfriend ul.style_user_notfriend li").click(
		function() { 
			if($(this).find("input:checkbox").is(":checked")){
				$(this).find("input:checkbox").removeAttr("checked").parent().parent().removeClass("selected");
			}
			else {
				$(this).find("input:checkbox").attr("checked","checked").parent().parent().addClass("selected");
			}
		}
	);
	

	</script>';
}

function get_list($gru){
	if($gru == 'all'){
		$fol = "`groupname` = '".name_db_friendlist."'";
	} else {
		$fol = "`id` = '".$gru."'";
	}
	$get_member = '';
	include("../connect.php");
	$sql = 	"SELECT `member`";
	$sql .= " FROM `user_groupview`";
	$sql .= " WHERE `owner` = ".$_SESSION[sess_login]['id']." AND ".$fol."";
	$result = mysql_query($sql, $conn);
	if(mysql_num_rows($result)==1){
	  $row = mysql_fetch_row($result);
	  $get_member = str_replace(':',',',$row[0]);
	  return $get_member;
	}
	else {
	  return '';
	}
	mysql_free_result($result);	
	mysql_close($conn);
}

	// 0 = id
	// 1 = username
	// 2 = fullname
	// 3 = email
	// 4 = avatar

function load_myfriend($gru, $val){
	global $avatar_redir, $avatar_default, $limitrecord_friend;
	$array_list_friend='';
	$flag = false;
	$get_member = get_list($gru);

	include("../connect.php");
	if($get_member!=''){
	  $merg_sql = "SELECT a.`id`, a.`username`, b.`fullname`, b.`email`, b.`avatar`";
	  $merg_sql .= " FROM `user_account` a,`user_info` b";
	  $merg_sql .= " WHERE a.`id` = b.`id` AND a.`status` = '1' AND  a.`id` IN (".$get_member.")";
	  
	  $total = @mysql_num_rows(@mysql_query($merg_sql)); 
	  $total_page = ceil($total/$limitrecord_friend);
	  $start_user = $val*$limitrecord_friend;
	  
	  $merg_sql .= " ORDER BY a.`username` ASC LIMIT ".$start_user.",".$limitrecord_friend."";
	  $result2 = @mysql_query($merg_sql, $conn);
	  if (@mysql_num_rows($result2)!=0){
		  while ($row2 = @mysql_fetch_row($result2)){ 
			  $array_list_friend[] = $row2;
		  }
		  $flag = true;
	  }
	  @mysql_free_result($result2);			
	}
	mysql_close($conn);
	if($gru != 'all')
	echo '
	<a onclick="javascript:add_member_list(\''.$gru.'\');"><div id="bt_edit_member" class="uix-button"><img src="./style/default/add_friend.png"> Add / Remove friend\'s group </div></a>
	<a onclick="javascript:edit_group(\''.$gru.'\');"><div id="bt_edit_group" class="uix-button"><img src="./style/default/add_friend.png"> Edit Group </div></a>
	<div id="edit_group">
	</div>
	';

	if($flag){
		echo '<ul class="style_user_list">';
		foreach($array_list_friend as $user_friend => $val_user){
			echo '<li>';
			if(!file_exists($avatar_redir.$val_user['4']) || $val_user['4'] == ''){
				$link_image = $avatar_default;
			} else {
				$link_image = $avatar_redir.$val_user['4'];
			}
			echo '<div class="username_list_friend">'. $val_user['1'] .'</div>';
			echo '<div class="avatar"><img src="'. $link_image .'"></div>';
			echo '<div class="userfullname_list_friend"> '. $val_user['2'] .' </div>';
			echo '</li>';
		}
		echo '</ul>';
		
		if($total_page!=1){
		echo '<div class="page_break"><ul>';
			if($val!=0){ echo '<li class="uix-button" onclick="load_myfriend(\''.$gru.'\',\''.($val-1).'\')"><< Rev &nbsp;</li>'; }
			for($i = 0; $i<$total_page; $i++){
				if($i == $val){ $active = 'uix-button-active';} else { $active = ''; }
				echo '<li onclick="load_myfriend(\''.$gru.'\','.$i.')" class="uix-button '.$active.'">';
					echo $i+1;
				echo '</li>';
			}
			if($val!= ($total_page-1)){ echo '<li class="uix-button" onclick="load_myfriend(\''.$gru.'\',\''.($val+1).'\')">Next >></li>'; }
			echo '</ul></div>';
		}
		
		
	}
	else{
		echo 'You have to add some friend';
	}
}


function load_randomuser(){	
	global $avatar_redir, $avatar_default, $limitrecord_userrandom;
	$array_list_user='';
	$flag = false;
	
	$get_member = get_list('all');
	
	if($get_member!=''){
		$get_member = ",".$get_member;
	}

	include("../connect.php");
	
	$sql1  = "SELECT a.`id`, a.`username`, b.`fullname`, b.`email`, b.`avatar`";
	$sql1 .= " FROM `user_account` a,`user_info` b";
	$sql1 .= " WHERE a.`id` = b.`id` AND a.`status` = '1' AND a.`id` NOT IN (".$_SESSION[sess_login]['id'].$get_member.")";
	$sql1 .= " ORDER BY a.`id` DESC LIMIT ".$limitrecord_userrandom."";
	$result1 = @mysql_query($sql1, $conn);

	if (@mysql_num_rows($result1)!=0){
		while ($row1 = @mysql_fetch_row($result1)){ 
			$array_list_user[] = $row1;
		}
		$flag = true;
	}
	@mysql_free_result($result1);
	mysql_close($conn);
	if($flag){
		shuffle($array_list_user);
		echo '<ul class="style_user_notfriend">';
		foreach($array_list_user as $each_user => $val){
			echo '<li>';
			if(!file_exists($avatar_redir.$val['4']) || $val['4'] == ''){
				$link_image = $avatar_default;
			} else {
				$link_image = $avatar_redir.$val['4'];
			}
			echo '<div class="username_list"> '. $val['1'] .' <br /> '. $val['2'] .' </div>';
			echo '<div class="avatar"><img src="'. $link_image .'"></div>';
			echo '<div class="option_list_friend" id="bt_'.$val['0'].'"><button class="uix-button" onclick="add_friend(\''.$val['0'].'\')"> &nbsp;<img src="./style/default/add_friend.png"> &nbsp;Add &nbsp; </button></div>';
			echo '</li>';
		}
		echo '</ul>';
	}

echo '	<script> $(".style_user_notfriend li").hover(
		function(){$(this).find("div.username_list").animate({width: "show"});},
		function(){$(this).find("div.username_list").animate({width: "hide"});});
		</script>
	';
}

function load_grouplist($val,$pos){
	
	$get_group = '';
	include("../connect.php");
	$sql2  = "SELECT `id`,`groupname`";
	$sql2 .= " FROM `user_groupview`";
	$sql2 .= " WHERE `owner` = ".$_SESSION[sess_login]['id']."";
	$result2 = @mysql_query($sql2, $conn);
	if(@mysql_num_rows($result2)!=0){
		while ($row2 = @mysql_fetch_row($result2)){ 
			$get_group[] = $row2;
		}
		
		foreach($get_group as $each_group => $value_group){
			echo '<li>';
			if($value_group['1'] != name_db_friendlist){
				if($value_group['0'] == $pos){
					echo '<a href="'.$val.$value_group['0'].'"><div class="active_group">'.$value_group['1'].'</div></a>';
					echo '<script> $("#name_group_change").html("GROUP: &nbsp; &nbsp;'.$value_group['1'].'");</script>';
				}
				else{
					echo '<a href="'.$val.$value_group['0'].'"><div>'.$value_group['1'].'</div></a>';
				}
			}
			else {
				echo '<script> $("#name_group_change").html("All Friends");</script>';
			}
			echo '</li>';
		}
	}
	else {
	  echo '<script> $("#name_group_change").html("All Friends");</script>';
	}
	@mysql_free_result($result2);	
	mysql_close($conn);
}

function load_form_newgroup(){
	echo '
<form onsubmit="return false;" name="form_new_group" id="form_new_group">
	<table border="0" cellpadding="5" cellspacing="5">
	  <tr>
		<td width="100" height="41" align="right" valign="middle">&nbsp; Group Name:  &nbsp;</td>
		<td width="325" align="left" valign="middle"><input type="text" name="groupname" id="groupname" style="width:300px;"></td>
		<td width="90" align="left" valign="middle"><input type="submit" name="Submit" value="&nbsp; Create &nbsp;"></td>
	  </tr>
	</table>
</form>
<script>
$("#form_new_group").submit( function() {
	var flag_submit = true;
	$("span.error").remove();

	if ($.trim($("#groupname").val()) == "") {
	  $("#groupname").after(error_text);
	  flag_submit = false;
	}
	if(flag_submit){
	
		var content = $("#form_new_group").serializeArray();
		$.ajax({
			type: "GET",
			url: "./module/user/function_friend.php",
			data: {act:"newgroup", val:content},
			success: function(data) {
				if(data==0){
					 alert ("Error transfer");
				} else if(data=="1") {
					$("#new_group").html(\'<span class="success_span">Group has been created</span>\');	
					window.document.location.reload();
				} else if(data=="2") {
					alert ("Error cannot create new group");
				} else {
					alert ("Error: "+ data);
				}
			},
			error: function (){ alert ("Cannot get function file"); }
		});
		return false;
		}
	return false;

});
</script>
';
}


function load_form_editgroup($val){
	include("../connect.php");
	$sql = 	"SELECT `groupname`";
	$sql .= " FROM `user_groupview`";
	$sql .= " WHERE `owner` = ".$_SESSION[sess_login]['id']." AND `id` = ".$val."";
	$result = mysql_query($sql, $conn);
	if(mysql_num_rows($result)==1){
	  $row = mysql_fetch_row($result);
	  $get_name = $row[0];

	echo '
<br />
<form onsubmit="return false;" name="form_edit_group" id="form_edit_group">
	<input type="hidden" name="id_f" value="'.$val.'">
	<table border="0" cellpadding="5" cellspacing="5" width="690">
	  <tr>
		<td width="100" height="41" align="right" valign="middle">&nbsp; Group Name:  &nbsp;</td>
		<td width="275" align="left" valign="middle"><input type="text" name="group_editname" id="group_editname" style="width:260px;" value = "'.$get_name.'"></td>
		<td width="270" align="left" valign="middle"><input type="submit" name="Submit" value="&nbsp; Save &nbsp;"> <input type="button" name="cancel" value=" Cancel " onclick="javascript:$(\'#edit_group\').slideUp();"> <input type="button" name="delete" value=" Delete this group " onclick="delete_group(\''.$val.'\');"></td>
	  </tr>
	</table>
</form>
<script>
$("#form_edit_group").submit( function() {
	var flag_submit = true;
	$("span.error").remove();

	if ($.trim($("#group_editname").val()) == "") {
	  $("#group_editname").after(error_text);
	  flag_submit = false;
	}
	if(flag_submit){
		var content = $("#form_edit_group").serializeArray();
		$.ajax({
			type: "GET",
			url: "./module/user/function_friend.php",
			data: {act:"editgroup", val:content},
			success: function(data) {
				if(data==0){
					 alert ("Error transfer");
				} else if(data=="1") {
					$("#edit_group").html(\'<span class="success_span">Name has been saved</span>\');	
					window.document.location.reload();			
				} else if(data=="2") {
					alert ("Error cannot save name");
				} else {
					alert ("Error: "+ data);
				}
			},
			error: function (){ alert ("Cannot get function file"); }
		});
		return false;
		}
	return false;

});

function delete_group(fol){
	var urlcurrent = window.document.location.href;
	var urlredirect = urlcurrent.substr(0,urlcurrent.indexOf("&gid"));
	$.ajax({
	  type: "GET",
	  url: "./module/user/function_friend.php",
	  data: {act:"deletegroup", val:fol},
	  dataType: "html",
	  success: function(data) {
		  if(data==0){
			  alert ("Error transfer");
		  } else if(data==1) {
			  $("#edit_group").html("<span class=\'success_span\'> Group has been deleted </span>");
			  window.document.location.href = urlredirect;
		  } else if(data==2) {
			  alert ("ERROR cannot delete");
		  } else {
			  alert ("Unknown Error \n"+ data );
		  }
	  },
	  error: function (){ alert ("Cannot get function file");}
	});
}


</script>
';
	}
	else {
	  return '';
	}
	mysql_free_result($result);	
	mysql_close($conn);
}

?>
